import axios from './axios'
import { Session } from '@/utils/storage'

const apiAxios = ({
  headers,
  method,
  url,
  data,
  params,
  responseType
}: http.AxiosRequest): http.CustomPromise => {
  return new Promise((resolve, reject) => {
    const cookie = Session.get('cookie')
    if (method === 'GET') {
      params = Object.assign({}, params, { cookie })
    } else {
      data = Object.assign({}, data, { cookie })
    }
    axios({
      headers,
      method,
      url,
      params,
      data,
      responseType
    })
      .then((res) => {
        // 200:服务端业务处理正常结束
        if (res.status === 200) {
          if (res.data.code === 200) {
            resolve({
              success: true,
              message: res.data?.message || 'success',
              data: res.data,
              code: res.data?.code || '000000',
              dataType: res.data?.dataType || 'rpc'
            })
          } else {
            resolve({
              success: false,
              message: res.data?.message || url + '请求失败',
              data: res.data?.data,
              code: res.data?.code,
              dataType: res.data?.dataType || 'rpc'
            })
          }
        } else {
          resolve({
            success: false,
            message: res.data?.message || url + '请求失败',
            data: null,
            code: '',
            dataType: res.data?.dataType || 'rpc'
          })
        }
      })
      .catch((err) => {
        const message =
          err?.data?.errorMessage || err?.message || url + '请求失败'
        // eslint-disable-next-line
        reject({ status: false, message, data: null })
      })
  })
}

/**
 * GET类型的网络请求
 */
const getReq = ({ headers, url, data, params, responseType }: http.AxiosRequest) => {
  return apiAxios({
    headers,
    method: 'GET',
    url,
    data,
    params,
    responseType
  })
}

/**
 * POST类型的网络请求
 */
const postReq = ({
  headers,
  url,
  data,
  params,
  responseType
}: http.AxiosRequest) => {
  return apiAxios({
    headers,
    method: 'POST',
    url,
    data,
    params,
    responseType
  })
}

/**
 * PUT类型的网络请求
 */
const putReq = ({ headers, url, data, params, responseType }: http.AxiosRequest) => {
  return apiAxios({
    headers,
    method: 'PUT',
    url,
    data,
    params,
    responseType
  })
}

/**
 * DELETE类型的网络请求
 */
const deleteReq = ({
  headers,
  url,
  data,
  params,
  responseType
}: http.AxiosRequest) => {
  return apiAxios({
    headers,
    method: 'DELETE',
    url,
    data,
    params,
    responseType
  })
}

export { getReq, postReq, putReq, deleteReq }
